package com.zsr.rabbitmq.eight;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.zsr.rabbitmq.utils.RabbitMqUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 死信  消费者1，尝试产生死信
 *
 * @author zsr
 * @date 2021/8/9 17:26
 */
public class Consumer01 {
    //普通交换机
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    //死信交换机
    public static final String DEAD_EXCHANGE = "dead_exchange";
    //普通队列
    public static final String NORMAL_QUEUE = "normal_queue";
    //死信队列
    public static final String DEAD_QUEUE = "dead_queue";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMqUtils.getChannel();
        //声明普通交换机和死信交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE,BuiltinExchangeType.DIRECT);
        //声明普通队列
        Map<String,Object> arguments=new HashMap<>();
        //设置过期时间(也可以在生产者发送时设置)
        //arguments.put("x-message-ttl",10000);
        //正常队列设置死信交换机是谁
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        //设置死信RoutingKey,根据这个转发到死信队列
        arguments.put("x-dead-letter-routing-key","lisi");
        //设置正常队列的最大长度
        //arguments.put("x-max-length",6);
        channel.queueDeclare(NORMAL_QUEUE,false,false,false,arguments);

        //----------------------------------------------------------------------
        //声明死信队列
        channel.queueDeclare(DEAD_QUEUE ,false,false,false,null);

        //绑定普通的交换机与普通队列
        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,"zhangsan");
        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,"lisi");

        System.out.println("等待接收消息");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            /**
             * 3.测试死信队列产生条件3：队列达到最大长度
             */
            String message=new String(delivery.getBody(), "UTF-8");
            if(message.equals("info5")){
                /**
                 * 参数二 是否返回队列，false的回话会进入死信队列
                 */
                channel.basicReject(delivery.getEnvelope().getDeliveryTag(),false);
                System.out.println("consumer01等待接收消息"+message+",此消息拒绝");
            }else{
                System.out.println("consumer01等待接收消息"+message);

            }
        };
        //第二个参数false开启手动应答
        channel.basicConsume(NORMAL_QUEUE, false, deliverCallback, (consumerTag) -> {
        });
    }
}
